//
//  AppDatabase.swift
//  test-ios
//
//  Created by wyz5204 on 2023/4/1.
//

import Foundation
import GRDB

struct AppDatabase {
    
    static var migrator : DatabaseMigrator {
        var migrator = DatabaseMigrator.init()
        migrator.registerMigration("createLibrary") { db in
            
            print("migrator")
            try db.create(table: "grdbLoggedDay") { table in
                table.column("id", .integer).primaryKey()
                table.column("date", .text).notNull()
                table.column("isWorking", .boolean).notNull().defaults(to: false)
            }
            
            try db.create(table: "grdbProject") { table in
                table.column("id", .integer).primaryKey()
                table.column("name", .text).notNull()
            }
            
            try db.create(table: "grdbLoggedTimeRecord") { table in
                table.column("id", .integer).primaryKey()
                table.column("date", .text).notNull()
                table.column("description", .text)
                table.column("minutesSpent", .integer).notNull()
                table.column("dateId", .integer)
                    .references("grdbLoggedDay", onDelete: .cascade)
                table.column("projectId", .integer)
                    .references("grdbProject")
            }
            
            try db.create(table: "joke_table", body: { table in
                table.column("id", .integer).primaryKey()
                table.column("reason", .text)
                table.column("errorCode", .integer)
            })
        }
        return migrator
    }
    static var migrator_v2 : DatabaseMigrator{
        var migrator = DatabaseMigrator.init()
        migrator.registerMigration("createLibrary2") { db in
            print("migrator_v2")
            try db.create(table: "joke_table", body: { table in
                table.column("id", .integer).primaryKey()
                table.column("reason", .text)
                table.column("errorCode", .integer)
            })
        }
        return migrator
    }
    static func openDB(_ path : String) throws -> DatabaseQueue {
        let db = try DatabaseQueue.init(path: path)
        try? migrator.migrate(db)
        try? migrator_v2.migrate(db)
        return db
    }
}
